package com.zf.admin.utils.jwt;

import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LJH
 * @date 2019/7/16-6:16
 * @QQ 1755497577
 */
public class MyFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        response.setCharacterEncoding("utf-8");
        String token = null;
        for (Cookie c : request.getCookies()) {
            if (c.getName().equals("authorization") || c.getName().equals("Authorization")) {
                token = c.getValue();
                break;
            }
        }
        logger.info("路径：" + request.getContextPath());

        if (token == null) {
            ((HttpServletResponse) servletResponse).sendRedirect(request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/login");
            return;
        }
        Claims claims = JwtService.parsePersonJWT(token);
        if (claims == null) {
            ((HttpServletResponse) servletResponse).sendRedirect(request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/login");

        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}